package cn.bdqn.hospital.dao.impl;

import cn.bdqn.hospital.dao.DrugDao;
import cn.bdqn.hospital.entity.Drug;
import cn.bdqn.hospital.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class DrugDaoImpl implements DrugDao {
    QueryRunner queryRunner =new QueryRunner();

    /**
     * 查询所有药品
     *
     * @return
     * @throws SQLException
     */
    @Override
    public List<Drug> getAll() throws SQLException {
        List<Drug> drugList =null;
        String sql="select * from drug;";
        drugList=queryRunner.query(sql,new BeanListHandler<Drug>(Drug.class));
        return drugList;
    }

    /**
     * 通过id查询
     *
     * @param drugId
     * @return
     * @throws SQLException
     */
    @Override
    public Drug getDrugBydrugId(Integer drugId) throws SQLException {
        Drug drug =null;
        String sql="select * from drug where drugId=?;";
        drug =queryRunner.query(sql,new BeanHandler<Drug>(Drug.class),drugId);
        return drug;
    }


    /**
     * 通过名称查询药品
     *
     * @param drugName
     * @return
     * @throws SQLException
     */
    @Override
    public Drug getDrugBydrugName(String drugName) throws SQLException {
        Drug drug =null;
        String sql="select * from drug where drugName=?;";
        drug = queryRunner.query(DruidUtils.getConnection(),sql,new BeanHandler<Drug>(Drug.class),drugName);
        return drug;
    }

    /**
     * 新增药品
     *
     * @param drug
     * @return
     * @throws SQLException
     */
    @Override
    public int add(Drug drug) throws SQLException {
        int num=0;
            String sql="INSERT INTO drug(drugname, drugclassid, drugprice, drugmount) VALUES (?,?,?,?);";
            num=queryRunner.update(DruidUtils.getConnection(),sql,drug.getDrugName(),drug.getDrugClassId(),drug.getDrugPrice(),drug.getDrugMount());
        return num;
    }

    /**
     * 修改药品
     *
     * @param drug
     * @return
     * @throws SQLException
     */
    @Override
    public int update(Drug drug) throws SQLException {
        int num=0;
        String sql = "update drug set drugName=? where drugId=?;";
        num=queryRunner.update(DruidUtils.getConnection(),sql,drug.getDrugId());
        return 0;
    }

    /**
     * 删除药品
     *
     * @param drugId
     * @return
     * @throws SQLException
     */
    @Override
    public int delete(Integer drugId) throws SQLException {
        int num=0;
        String sql = "delete  from Drug where drugId=?;";
        num=queryRunner.update(DruidUtils.getConnection(),sql,drugId);
        return num;
    }
}
